package com.eliza.security.controller;

import com.eliza.security.common.CommonResult;
import com.eliza.security.fronts.LoginModel;
import com.eliza.security.model.Register;
import com.eliza.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@RestController
@RequestMapping("/user")
public class UserController {


    @Value("${jwt.tokenHead}")
    String tokenHead;

    @Autowired
    private UserService userService;

    @PreAuthorize("hasAuthority('wx:product:read')")
    @GetMapping("/user")
    public String userTest(){
        return "恭喜访问成功了！！！";
    }

    @GetMapping("/login")
    public CommonResult login(@RequestBody LoginModel loginModel){
        HashMap<String, String> data = new HashMap<>();
        String token = null;
        try {
            token = userService.login(loginModel);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.validateFailed("用户名或密码错误");
        }
        if (StringUtils.isEmpty(token)){
            return CommonResult.validateFailed("用户名或密码错误");
        }
        data.put("tokenHead",tokenHead);
        data.put("access_token",token);
        // localStorage.setItem("Authorization","Bearer sdsdfdfds")
        // $ajax{data:{},type:"",header:{"Authorization":"Bearer sdsdfdfds"}}
        return CommonResult.success(data);
    }

    @PostMapping("/register")
    public CommonResult register(Register register){

    }
}
